using Microsoft.EntityFrameworkCore;
using FServer.Core.Entities;
using FServer.Core.Interfaces;
using FServer.Infrastructure.Data;

namespace FServer.Infrastructure.Services;

/// <summary>
/// 版本管理服务实现
/// </summary>
public class VersionService : IVersionService
{
    private readonly GameDbContext _context;
    private readonly ILogger<VersionService> _logger;

    public VersionService(GameDbContext context, ILogger<VersionService> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<VersionCheckResult> CheckVersionAsync(string clientVersion, string platform)
    {
        try
        {
            _logger.LogInformation("检查客户端版本: {ClientVersion}, 平台: {Platform}", clientVersion, platform);

            // 解析客户端版本
            var clientVersionParts = ParseVersion(clientVersion);
            if (clientVersionParts == null)
            {
                return new VersionCheckResult
                {
                    NeedUpdate = false,
                    ForceUpdate = false,
                    ErrorMessage = "无效的客户端版本格式"
                };
            }

            // 获取最新版本
            var latestVersion = await _context.ClientVersions
                .Where(v => v.IsEnabled && v.VersionType == "Release")
                .OrderByDescending(v => v.MajorVersion)
                .ThenByDescending(v => v.MinorVersion)
                .ThenByDescending(v => v.PatchVersion)
                .FirstOrDefaultAsync();

            if (latestVersion == null)
            {
                return new VersionCheckResult
                {
                    NeedUpdate = false,
                    ForceUpdate = false,
                    ErrorMessage = "未找到可用版本"
                };
            }

            // 获取当前版本信息
            var currentVersion = await _context.ClientVersions
                .FirstOrDefaultAsync(v => v.Version == clientVersion);

            // 比较版本
            var versionComparison = CompareVersions(clientVersionParts, 
                (latestVersion.MajorVersion, latestVersion.MinorVersion, latestVersion.PatchVersion));

            var needUpdate = versionComparison < 0;
            var forceUpdate = latestVersion.IsForceUpdate && versionComparison < 0;

            // 如果需要更新，获取更新文件
            var updateFiles = new List<UpdateFile>();
            if (needUpdate)
            {
                updateFiles = await _context.UpdateFiles
                    .Where(f => f.VersionId == latestVersion.Id)
                    .ToListAsync();
            }

            return new VersionCheckResult
            {
                NeedUpdate = needUpdate,
                ForceUpdate = forceUpdate,
                LatestVersion = latestVersion,
                CurrentVersion = currentVersion,
                UpdateFiles = updateFiles,
                UpdateDescription = latestVersion.UpdateContent
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "版本检查失败: {ClientVersion}", clientVersion);
            return new VersionCheckResult
            {
                NeedUpdate = false,
                ForceUpdate = false,
                ErrorMessage = "版本检查失败"
            };
        }
    }

    public async Task<List<UpdateFile>> GetUpdateFilesAsync(Guid versionId)
    {
        return await _context.UpdateFiles
            .Where(f => f.VersionId == versionId)
            .OrderBy(f => f.FileType)
            .ThenBy(f => f.FileName)
            .ToListAsync();
    }

    public async Task<ClientVersion?> GetVersionAsync(Guid versionId)
    {
        return await _context.ClientVersions
            .FirstOrDefaultAsync(v => v.Id == versionId);
    }

    public async Task<ClientVersion> CreateVersionAsync(ClientVersion version)
    {
        _context.ClientVersions.Add(version);
        await _context.SaveChangesAsync();
        
        _logger.LogInformation("创建新版本: {Version}", version.Version);
        return version;
    }

    public async Task<ClientVersion> UpdateVersionAsync(ClientVersion version)
    {
        version.UpdatedAt = DateTime.UtcNow;
        _context.ClientVersions.Update(version);
        await _context.SaveChangesAsync();
        
        _logger.LogInformation("更新版本: {Version}", version.Version);
        return version;
    }

    /// <summary>
    /// 解析版本号
    /// </summary>
    private (int major, int minor, int patch)? ParseVersion(string version)
    {
        try
        {
            var parts = version.Split('.');
            if (parts.Length != 3) return null;

            var major = int.Parse(parts[0]);
            var minor = int.Parse(parts[1]);
            var patch = int.Parse(parts[2]);

            return (major, minor, patch);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 比较版本号
    /// </summary>
    /// <returns>-1: 需要更新, 0: 相同, 1: 客户端更新</returns>
    private int CompareVersions((int major, int minor, int patch) client, (int major, int minor, int patch) server)
    {
        if (client.major != server.major)
            return client.major.CompareTo(server.major);
        
        if (client.minor != server.minor)
            return client.minor.CompareTo(server.minor);
        
        return client.patch.CompareTo(server.patch);
    }
}
